import React, { Component } from 'react'
import { Button, Table, Steps, Row, Col, Select, Input, Form, message, Popconfirm, Radio } from 'antd';
import { connect } from 'react-redux';
import './categoryMgr.scss'
import {actionCreators}  from './store'
import { getAllMetaData, saveNewCateRegFriPage, saveNewCateRegSecPage, deleteResourceById} from '../../../api/resourceCategory/resourceCategory'
import { valueToDataType, valueToTF} from '../commonConfig'
const { Step} = Steps
const { Option} = Select
const { Column} = Table
const titleStyle={
  color:'rgb(0,126,220)',height:54.6,width:520,backgroundColor:'#f0f3f6',position:'absolute',left:0,top:0,display:'flex',
  alignItems:'center',paddingLeft:24,fontWeight:'bold',borderBottom:'2px solid #e5e6e8',zIndex:2
}
const footerStyle={
  backgroundColor:'#e6eef5',width:520,height:53,position:'absolute',left:0,bottom:0,
  display:'flex',alignItems:'center',justifyContent:'center'
}

const formItemLayout = {
  labelCol: { span: 10 },
  wrapperCol: { span: 6 },
};
const formItemStyle={color:'rgb(0,126,220)',fontWeight:'bold'};
class EditResource extends Component {
  constructor() {
    super()
    this.state = {
      current: 0,
      dataSource: [],
      checkedData: [],
      selectedRowKeys: [],
      showSymbol: 0,//0表示新增按钮显示，1表示保存按钮显示
      disabledInput: false,
      count: 0,
      curMetaId: '',
      initialData: {}
    }
    this.columns = [
      {
        title: '序号',dataIndex: 'id',key: 'id',width: 100,
        render: (text, record, index)=><span>{index+1}</span>
      },
      {
        title: '英文名',dataIndex: 'name',key: 'name',width: 150,
      },
      {
        title: '中文名',dataIndex: 'cnName',key: 'cnName',width: 100,
      },
      {
        title: '数据类型',dataIndex: 'dataType',key: 'dataType',width: 100,
        render:(text,record)=>{return <span >{valueToDataType[text]}</span>}
      },
      {
        title: '是否主键',dataIndex: 'isPk',key: 'isPk',width: 80,
        render:(text,record)=>{return <span >{valueToTF[text]}</span>}
      },
      {
        title: '是否为空',dataIndex: 'isNull',key: 'isNull',width: 100,
        render:(text,record)=>{return <span >{valueToTF[text]}</span>}
      },
      {
        title: '是否增量',dataIndex: 'increment',key: 'increment',width: 100,
        render:(text,record)=>{return <span >{valueToTF[text]}</span>}
      },
      {
        title: '操作',dataIndex: 'action',key: 'action',width: 150,
        render: (text, record) => {
          return (
            <div>
              <Popconfirm title="确认删除?"
                onConfirm={() => this.handleDeleteClick(record.key)}
                okText="确定" cancelText="取消"
              >
                <Button size="small" style={{ backgroundColor: 'rgb(238, 177, 63)', marginLeft: 10 }}>删除</Button>
              </Popconfirm>
            </div>
          )
        }
      },
    ]

  }
  componentWillMount() {
    this.setState({
      initialData: this.props.initialData,
      checkedData: this.props.passDataSource
    })
  }
  onChange = current => {
    this.setState({ current });
  };

  componentDidMount(){
    this.props.onRef(this);
  }

  handleShareTypeChange  =e => {
    console.log(e)
    this.formRef.current.setFieldsValue({
      resourceForm:e
    })
  }
  resetForm=()=>{
    this.searchForm.current.resetFields();
    this.searchForm.current.setFieldsValue({category: ''})
  }

  handleEditSave =() => {
    let { dataSource, selectedRowKeys, initialData} = this.state
    console.log(initialData)
    let newArr = this.state.dataSource.filter(item => selectedRowKeys.indexOf(item.dataId)>-1)
      let obj = {catalogueNumber: this.props.curNumber, ...initialData, userId: '11'}
      this.props.saveNewCateRegFriPage(obj)
      // saveNewCateRegFriPage(obj).then(res => {})
      let dataIds = selectedRowKeys;
      let obj2 = {dataIds: dataIds, resourceId: parseFloat(initialData.resourceId)} 
      this.props.saveNewCateRegSecPage(obj2)
      // saveNewCateRegSecPage(obj2).then(res => {   
      // })
      this.setState({
        checkedData: newArr, showSymbol: 0
      })
  }

  handleSearch =() => {
    if(this.state.curMetaId === '') {
      message.info('请选择元数据类型')
    }
    else {
      getAllMetaData({metaId: this.state.curMetaId}).then( res => {
        if(res.data.metaData.code === 'success') {
          this.setState({dataSource: res.data.data})
        }
      })
    }
    console.log('search', this.searchForm.current.getFieldsValue())
  }

  hanldeNextStep = () => {
    this.formRef.current.validateFields().then(values => {
      console.log(values);
      let obj = {catalogueNumber: this.props.curNumber, ...values, userId: '11'}
      this.setState({initialData: values, current: 1})
      this.props.setFormInitialData(obj)
    }).catch(err=>{
      console.log(err)
    });    
  }

  handlePrevious = () => {
    this.setState({current: 0})
  }

  handleAddChange = (value)=> {
    this.setState({ showSymbol: value})
  }

  handleMetaTypeChange = e => {
    this.setState({curMetaId: e})
  }
  formRef = React.createRef();
  searchForm = React.createRef()

  onSelectChange = selectedRowKeys => {
    console.log('onSelectChange', selectedRowKeys)
    this.setState({selectedRowKeys})
  }
  render() {
    console.log('this.props.form', this.form)
    const {current, initialData, selectedRowKeys, showSymbol, disabledInput } = this.state
    console.log('initialData', initialData)
    const {metedataTypes} = this.props
    const validateMessages = {
      required: "请输入",
    };
    const rules={required:true}
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange
    }

    return (
      <div>
        <Steps current={current} onChange={this.onChange}>
          <Step title='填写资源基本信息'>
          </Step>
          <Step title='编辑资源数据项'>
          </Step>
        </Steps>
        {
          current === 0&& 
          <div>
          <Form labelCol={{span:24}} wrapperCol={{span:20}} initialValues={this.props.initialData} validateMessages={validateMessages} ref={this.formRef}>
          <Row>
            <Col span={12}>
            <Form.Item style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源分类</span>} rules={[rules]} name='wholeName'>
                <Input disabled/>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源名称</span>} rules={[rules]} name='resourceName'>
                <Input />
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>共享类型</span>} rules={[rules]} name='shareType'>
                <Select placeholder='请选择类别'>
                  <Select.Option value={0}>有条件共享</Select.Option>
                  <Select.Option value={1}>无条件共享</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>共享方式</span>} rules={[rules]} name='shareMode'>
                <Select placeholder='请选择类别'>
                  <Select.Option value={1}>平台共享方式</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源格式</span>} rules={[rules]} name='resourceForm'>
                <Select placeholder='请选择类别' disabled>
                  <Select.Option value='2'>数据库</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>是否向社会开放</span>} rules={[rules]} name='isOpen'>
                <Radio.Group>
                  <Radio value={0}>不开放</Radio>
                  <Radio value={1}>开放</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>更换周期</span>} rules={[rules]} name='updateCycle'>
                <Select placeholder='请选择类别'>
                  <Select.Option value={1}>每时</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>关联分类</span>} >
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源代码</span>} rules={[rules]} name='resourceId'>
                <Input placeholder='请输入资源代码'disabled />
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源简称</span>} rules={[rules]} name='resourceAbbName'>
                <Input />
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>共享条件</span>} rules={[rules]} name='shareCondition'>
                <Input placeholder='请输入表中文名称'/>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>共享方式类型</span>}
               rules={[rules]} name='shareModeType'>
                <Select placeholder='请选择类别'  onChange={this.handleShareTypeChange}>
                  <Select.Option value={1}>数据库</Select.Option>
                  <Select.Option value={2}>文件</Select.Option>
                  <Select.Option value={3}>接口</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源格式类型</span>} rules={[rules]} name='resourceFormType'>
                <Select placeholder='请选择类别'>
                  <Select.Option value='1'>access</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>开放条件</span>} rules={[rules]} name='openCondition'>
                <Input placeholder='请输入表中文名称' disabled={disabledInput} />
              </Form.Item>
              <Form.Item   style={{marginBottom: '10px',}}label={<span style={formItemStyle}>摘要</span>} rules={[rules]} name='description'>
                <Input placeholder='请输入表中文名称'/>
              </Form.Item>
            </Col>
          </Row>
          <Row style={{border: '1px solid gray'}}>
            <p>提供方信息</p>
            <Row>
              <Col span={12}>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>资源提供方</span>} rules={[rules]} name='resourceProvider'>
                <Input disabled />
              </Form.Item>
              </Col>
              <Col span={12}>
              <Form.Item  style={{marginBottom: '10px'}} label={<span style={formItemStyle}>提供方代码</span>} rules={[rules]} name='catalogueNumber'>
                <Input disabled />
              </Form.Item>
              </Col>
            </Row>
          </Row>
        </Form>
        <div style={{padding: '10px 10px', margin: 'auto'}}>
          <Button type="primary" ghost onClick={this.props.onClose} size="small" >取消</Button>
          <Button type="primary" onClick={this.hanldeNextStep} style={{marginLeft: '30px'}} size="small" >下一步</Button>
        </div>
        </div>

        }
        {
          current === 1 &&
          <div className='topSearch'>
            {
              showSymbol === 0 && 
              <div>
                <Button type="primary" onClick={ e => this.handleAddChange(1)}>新增</Button>
                <div>
                <Table dataSource={this.state.checkedData} columns={this.columns} size='small' rowKey={record => record.dataId} />
                <div style={{padding: '10px 10px', margin: 'auto'}}>
                  <Button type="primary" ghost onClick={this.handlePrevious} size="small" >上一步</Button>
                  <Button type="primary" onClick={this.props.onClose} style={{marginLeft: '30px'}} size="small" >关闭</Button>
                </div>
              </div>
              </div>
            }
            {
              showSymbol === 1 &&
              <div>
                <Row>
                  <Form layout='inline' {...formItemLayout} ref={this.searchForm}>
                    <Form.Item label="元数据类别" name="meteadataType">
                      <Select style={{width: '100px'}} onChange={this.handleMetaTypeChange}>
                        {metedataTypes.map((item,index) => (
                          <Option key={index} value={item.metaId}>{item.name}</Option>
                        ))}
                      </Select>
                    </Form.Item>
                    <Form.Item label="英文名" name="englishName">
                      <Input style={{width: '80px'}} />
                    </Form.Item>
                    <Form.Item  label="中文名" name="chineseName">
                      <Input style={{width: '80px'}} />
                    </Form.Item>
                    <Button type="primary" onClick={this.handleSearch} >查询</Button>
                    <Button type="primary"   style={{marginLeft: '10px'}} onClick={this.resetForm}>重置</Button>
                  </Form>
                </Row>
                <Table dataSource={this.state.dataSource} size="middle"
                  rowKey={record => record.dataId}
                  rowSelection={rowSelection}  >
                  <Column title="序号" render={(text, record, index)=><span>{index+1}</span>} />
                  <Column title="英文名" dataIndex="name" key="name"/>
                  <Column title="中文名" dataIndex="cnName" key="cnName"/>
                  <Column title="数据类型" dataIndex="dataType" key="dataType" render={(text,record)=>{return <span >{valueToDataType[text]}</span>}} />
                  <Column title="是否主键" dataIndex="isPk" key="isPk" render={(text,record)=>{return <span >{valueToTF[text]}</span>}} />
                  <Column title="是否增量" dataIndex="increment" key="increment" render={(text,record)=>{return <span >{valueToTF[text]}</span>}} />
                  <Column title="是否为空" dataIndex="isNull" key="isNull" render={(text,record)=>{return <span >{valueToTF[text]}</span>}} />
                  {/* <Column title="操作" dataIndex="operation" key="operation"
                  render={(text,record)=>(<span><Button type="link">删除</Button></span>)}/> */}
                </Table>
                <div style={{padding: '10px 10px', margin: 'auto'}}>
                  <Button type="primary" ghost onClick={this.props.onClose} size="small" >取消</Button>
                  {
                    this.props.type === 'publishEdit' && 
                    <Button type="primary" onClick={this.handleEditSave} style={{marginLeft: '30px'}} size="small" >重新审核</Button>
                  }
                  {
                    this.props.type === 'unSubmitEdit' &&
                    <Button type="primary" onClick={this.handleEditSave} style={{marginLeft: '30px'}} size="small" >重新报送</Button>
                  }
                  {/* <Button type="primary" onClick={this.handleEditSave} style={{marginLeft: '30px'}} size="small" >保存</Button> */}
                </div>
              </div>
            }
          </div>
        }
      </div>
    )
  }
}

const mapState = (state) => {
  console.log('new Resource', state.getIn(['connection','dataSource']).toJS())
  console.log('new Reoso', state.getIn(['catemanage', 'initialData']).toJS())
  return {
    initialData: state.getIn(['catemanage', 'initialData']).toJS()
  }
}

const mapDispatch = (dispatch) => {
  return {
    setFormInitialData(data) {
      dispatch(actionCreators.setFormInitialData(data))
    },
    saveNewCateRegFriPage(data) {
      dispatch(actionCreators.saveCateRegFri(data))
    },
    saveNewCateRegSecPage(data) {
      dispatch(actionCreators.saveCateRegSec(data))
    }
    
  }
}
export default connect(mapState, mapDispatch)(EditResource)


